<?php

namespace Console\Controller;

use Console\Common\Library\Page;

class AdminController extends CstBaseController {

    private $adminLogic;

    public function _initialize() {
        parent::_initialize();
        $this->adminLogic = A('Common/Admin', 'Logic');
    }

    public function lists() {
        $this->display();
    }

    public function doGetList() {
        $data = I('post.');
        $page = $data['page'] ? $data['page'] : 1;
        $pageSize = 20;
        unset($data['page']);
        $data['state'] = 1;

        $listRes = $this->adminLogic->getList($page, $pageSize, $data);
        $data = $listRes['Result'];
        $total = $data['total'];
        $list = $data['list'];

        $PageLib = new Page($total, $pageSize);
        $pageHtml = $PageLib->show();
        $pageTotal = ceil($total / $pageSize);

        $this->assign("total", $total);
        $this->assign("pageTotal", $pageTotal);
        $this->assign("pageHtml", $pageHtml);
        $this->assign("list", $list);
        $this->assign("pageHtml", $pageHtml);
        $html = $this->fetch('doGetList');

        $res = array(
            "list" => $list,
            "html" => $html,
            "total" => $total,
            "pageTotal" => $pageTotal
        );
        $this->ajaxReturn(static::$res->suc("成功", $res));
    }

    public function add() {
        $this->display();
    }

    public function edit() {
        $id = I('get.id');
        $infoRes = $this->adminLogic->getInfo(array(
            "id" => $id,
            "static" => 1
        ));
        if (static::$res->isErr($infoRes)) {
            $this->sysErr($infoRes['Message']);
        }
        $info = $infoRes['Result'];
        if (empty($info)) {
            $this->sysErr("未找到用户信息");
        }
        $this->assign("info", $info);
        $this->display();
    }

    public function doAdd() {
        $data = I('post.');
        if ($data['password'] != $data['rep_password']) {
            $this->ajaxReturn(static::$res->err("两次密码不一致"));
        }
        $res = $this->adminLogic->addUser($data);
        $this->ajaxReturn($res);
    }

    public function doEdit() {
        $data = I('post.');
       
        if (!empty($data['rep_password']) || !empty(password)) {
            if ($data['password'] != $data['rep_password']) {
                $this->ajaxReturn(static::$res->err("两次密码不一致"));
            }
        }else{
            unset($data['password']);
        }

        $id = $data['id'];

        $userInfo = $this->getUserInfo();
        $userId = $userInfo['id'];

        $res = $this->adminLogic->updateUser($id, $userId, $data);
        $this->ajaxReturn($res);
    }
    
    public function doDel(){
        $id = I('post.id');
        $userInfo = $this->getUserInfo();
        $userId = $userInfo['id'];
        
        $res = $this->adminLogic->updateUser($id, $userId, array(
            "state"=>-1
        ));
        $this->ajaxReturn($res);
    }

}
